﻿

public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public bool IsBalanced(TreeNode root)
    {
        return GetHeight(root) == -1 ? false : true;
    }

    private int GetHeight(TreeNode root)
    {
        if (root is null) return 0;
        int res1 = GetHeight(root.left);
        int res2 = GetHeight(root.right);
        if (res1 == -1 || res2 == -1) return -1;
        return Math.Abs(res1 - res2) > 1 ? -1 : Math.Max(res1, res2) + 1;
    }

    public static void Main(string[] args)
    {
        int?[] root = [3, 9, 20, null, null, 15, 7];
        TreeNode rootNode = CreateBinaryTree(root);
        Solution solution = new Solution();
        bool res = solution.IsBalanced(rootNode);
        Console.WriteLine(res);
    }

    private static TreeNode CreateBinaryTree(int?[] root)
    {
        if (root is null || root.Length == 0 || root[0] is null)
        {
            return null;
        }

        Queue<TreeNode> queue = new Queue<TreeNode>();
        TreeNode rootNode = new TreeNode(root[0].Value);
        queue.Enqueue(rootNode);
        int i = 1;
        TreeNode node;

        while (i < root.Length && queue.Count > 0)
        {
            node = queue.Dequeue();
            if (root[i] is not null)
            {
                node.left = new TreeNode(root[i].Value);
                queue.Enqueue(node.left);
            }

            i++;
            if (i >= root.Length) break;
            if (root[i] is not null)
            {
                node.right = new TreeNode(root[i].Value);
                queue.Enqueue(node.right);
            }

            i++;
        }

        return rootNode;
    }
}
